import hashlib
import struct
from random import random

debug = True


def generate_gmt_time():
    if debug:
        return bytes.fromhex("6f38fca82dd7274de5f82316043de8be07d861e1c00b7c0d90991029483f4e07")
    else:
        # >I 大端4字节无符号整数
        random_bytes = struct.pack('>I', random.getrandbits(32))  # GMT Unix time
        random_bytes += bytes(random.getrandbits(8) for _ in range(28))  # Random bytes
        return random_bytes


# 派生密钥
def derive_keys(master_secret, client_random, server_random):
    def prf(secret, label, seed, length):
        p_hash = b''
        a = b''
        while len(p_hash) < length:
            a = hashlib.sha256(a + label + seed).digest()
            p_hash += hashlib.sha256(a + secret + seed).digest()
        return p_hash[:length]

    key_block = prf(master_secret, b"key expansion", client_random + server_random, 64)
    client_write_key = key_block[0:16]
    server_write_key = key_block[16:32]
    client_write_iv = key_block[32:48]
    server_write_iv = key_block[48:64]
    return client_write_key, server_write_key, client_write_iv, server_write_iv